<?php
namespace Content\Controller;
/**
* 分类管理界面
*/
class CatController extends CommonController{

    public function index(){
        $this->display();
    }

    public function edit(){
        $tree = new \Think\Tree();
		
        if($_GET['group_id']){

            //检测一下分组id是否合法
            if(M('CatsGroup')->find($_GET['group_id'])){
                $info['group_id'] = $_GET['group_id'];
            }

        }

        $m = D('Cats');
        $parentid = $_GET['parentid'] ? $_GET['parentid'] : 0;


        if($parentid){
            $info['group_id'] = $m->find($parentid);
            $info['group_id'] = $info['group_id']['group_id'];            
        }
        if($_GET['id']){
            $info = $m->find($_GET['id']);
            $parentid = $info['parentid'];
        }

		$map['group_id'] = $info['group_id'];
		$data = $m->where($map)->order('listorder asc')->select();

		foreach ($data as $r) {
			$r['selected'] = $r['id'] == $parentid ? 'selected' : '';
			$array[] = $r;
		}
		$str = "<option value='\$id' \$selected>\$spacer \$cat_name</option>";
		$tree->init($array);
		$select_categorys = $tree->get_tree(0, $str);
		$this->assign("select_categorys", $select_categorys);
        
        $this->info = $info;
        $this->display();
    }

    /**
    * @desc 根据分类ID，获取分类数据,接口
    */
    public function getdata_cat_tree(){
       // F('Cats/group_'.$_REQUEST['group_id'],NULL);
        _apiReturn(1,L('success'),CatController::getdata_cats($_REQUEST['group_id']));
    }

    /**
    * 非接口
    */
    public function getdata_cats($groupid){
        $treedata = F('Cats/group_'.$groupid);
        if(!$treedata){
            $treedata = CatController::_update_cache_tree($groupid);
        }
        return $treedata;
    }

    /**
	 * 固化app分类树存储
	 * @param unknown $appid
	 * @param unknown $groupid
	 */
	public function _update_cache_tree($groupid){
		$tree = new \Think\Tree();
		
		$map['group_id'] = $groupid;
        $m = D('Cats');
		$data = $m->where($map)->order('listorder asc')->select();
		$tree->init($data);
		$treedata = $tree->get_tree_array(0, $str);
        $result = CatController::_get_node_tpl($treedata,"");

		F('Cats/group_'.$groupid,$result);
		return $result;
	}

     /**
	 * 配合ajax_nodes
	 * @param unknown $datas
	 * @param unknown $result
	 * @return string
	 */
	public function _get_node_tpl($datas,$result){
		$results = array();
		foreach ($datas as $data){
			$res= array(
					'id' => $data['id'],
					'parentid' => $data['parentid'],
					'name' => $data['cat_name'],
                    'key' => $data['cat_desc'],
					'spread' => true
			);
			$results[] = $res;
			if($data['child']){
				$results[count($results)-1]['children'] = $this->_get_node_tpl($data['child'], $result);
			}
		}
		return $results;
	}

    public function edit_post(){
        if(IS_POST){
            if(!$_POST['group_id']){
                _apiReturn(0,"未设定所属分类，无法编辑");
            }
            $m = D('Cats');
            $data = $m->create($_POST);
            if($data['id']){
                if($m->save($data)){
                    F('Cats/group_'.$_POST['group_id'],NULL);
                    $this->success(L('success'));
                }else{
                    $this->error(L('error'));
                }
            }else{
                if($m->add($data)){
                    F('Cats/group_'.$_POST['group_id'],NULL);
                    $this->success(L('success'));
                }else{
                    $this->error(L('error'));
                }
            }
        }
    }

    public function del(){
        //更新缓存
        $m = D('Cats');
        $data = $m->find(I('ids'));
        F('Cats/group_'.$data['group_id'],NULL);
        $this->_del_cat($m,I('ids'));
        $this->success(L('success'));
    }

    /**
    * 递归删除分类
    */
    public function _del_cat($m,$id){
        $m->delete($id);
        $map['parentid'] = $id;
        $children = $m->where($map)->select();
        if(count($children) > 0){
            foreach($children as $child){
                $this->_del_cat($m,$child['id']);
            }
        }
    }

    public function group(){
        $this->display();
    }

    public function group_edit(){
        if($_GET['id']){
            $this->info = D('CatsGroup')->find($_GET['id']);
        }
        $this->display();
    }

    public function group_edit_post(){
        if(IS_POST){
            $m = D('CatsGroup');
            $data = $m->create($_POST);
            if(!$data){
                $this->error($m->getError());
            }else{
                if($data['id']){
                    $tmpId = $m->where('"group_key" = "'.$_POST['group_key'].'"')->getField('id');
                    if($tmpId && $tmpId != $_POST['id']){
                        _apiReturn(0,"分组Key已经被占用，不能使用该key");
                    }
                    $m->save($data);
                    $this->success(L('success'));
                }else{
                    $m->add($data);
                    $this->success(L('success'));
                }
            }
        }
    }

    public function group_del(){
        $this->_del(M('CatsGroup'),I('ids'));
    }

    public function getdata_group(){
        $p = I('p') ? I('p') : 1;
        $row = I('row') ? I('row') : 10;

        $m = D('CatsGroup');
        if(I('condition')) {
            $condition = condition_to_array(I('condition')); //加入条件参数
            foreach($condition as $key=>$val){
                if($key == 'uid'){
                    $map[$key] = $val;
                }else{
                    $map[$key] = array('like',"%{$val}%");
                }
            }
        }
        $data['data'] = $m->where($map)->page($p,$row)->select();
        //$data['sql'] = $m->_sql();
		$data['page']['total'] = $m->where($map)->count();
		$data['page']['cur'] = $p;
		$data['page']['row'] = $row;
		
		_apiReturn(1, L('success'), $data, $url); //数据获取成功
    }

}